import React, { useCallback } from 'react';
import { DynamicGameState, AiCallMode } from '../../types';
import CollapsibleSection from '../CollapsibleSection';
import EditableText from '../EditableText';

const EditableStatusValue = React.memo(({ path, value, isHighlighted, turnIndex, onUpdate }: { path: string; value: any; isHighlighted: boolean; turnIndex: number; onUpdate: (turnIndex: number, path: string, value: any) => void; }) => {
    const handleSave = useCallback((newValStr: string) => {
      let finalVal: any = newValStr;
      if (typeof value === 'object' && value !== null) {
        try { finalVal = JSON.parse(newValStr); } catch (e) { /* Keep as string */ }
      } else if(typeof value === 'number') {
        const parsedNum = parseFloat(newValStr);
        if(!isNaN(parsedNum)) finalVal = parsedNum;
      }
      onUpdate(turnIndex, path, finalVal);
    }, [onUpdate, turnIndex, path, value]);

    const editValue = (typeof value === 'object' && value !== null) ? JSON.stringify(value, null, 2) : String(value);
    const isLongText = editValue.length > 30 || editValue.includes('\n') || (typeof value === 'object' && value !== null);
    
    const displayValue = () => {
      if (typeof value === 'string') return value;
      if (typeof value === 'number' || typeof value === 'boolean') return String(value);
      if (value === null) return 'N/A';
      if (Array.isArray(value)) return `[${value.length} 项]`;
      if (typeof value === 'object') return '{...}';
      return '未知类型';
    };
    return (
      <EditableText initialValue={editValue} onSave={handleSave} textClassName="text-gray-200 ml-1 text-right flex-grow" inputClassName="bg-gray-600 text-gray-100 p-1 rounded w-full text-sm" isTextArea={isLongText} className="flex-grow">
        <span className={value !== null && value !== undefined && String(value).length > 0 ? 'text-gray-100' : 'text-gray-500'}>{displayValue()}</span>
      </EditableText>
    );
});

const renderDynamicStateRecursive = (state: DynamicGameState, currentPath: string, turnIdx: number, onUpdate: (turnIndex: number, path: string, value: any) => void, changedPaths: Set<string>, aiCallMode: AiCallMode): React.ReactElement[] => Object.entries(state).map(([key, value]) => {
    const newPath = `${currentPath}/${key}`;
    const displayKey = key.replace(/([A-Z])/g, ' $1').replace(/^./, str => str.toUpperCase());
    const isHybridMode = aiCallMode === AiCallMode.Hybrid;
    const isHighlighted = isHybridMode && changedPaths.has(newPath);
    const hasHighlightedChild = isHybridMode && Array.from(changedPaths).some(p => p.startsWith(`${newPath}/`));
    const defaultOpen = !isHybridMode || hasHighlightedChild || (isHighlighted && (typeof value !== 'object' || value === null));
    const highlightClass = isHighlighted ? 'bg-yellow-800/40 border border-yellow-600/60 rounded-md -mx-1 px-1' : '';

    if (typeof value === 'object' && value !== null && !Array.isArray(value)) {
      return (
        <div key={newPath} className={`my-1 ${highlightClass}`}>
          <CollapsibleSection
            title={displayKey}
            defaultOpen={defaultOpen}
            titleClassName={`text-sm font-medium ${isHighlighted || hasHighlightedChild ? 'text-yellow-300' : 'text-sky-300'}`}
          >
            <div className="ml-2 pl-2 border-l border-gray-600">
                {renderDynamicStateRecursive(value, newPath, turnIdx, onUpdate, changedPaths, aiCallMode)}
            </div>
          </CollapsibleSection>
        </div>
      );
    } else if (Array.isArray(value)) {
      return (
        <div key={newPath} className={`my-1 ${highlightClass}`}>
          <CollapsibleSection
            title={`${displayKey} (${value.length})`}
            defaultOpen={defaultOpen}
            titleClassName={`text-sm font-medium ${isHighlighted || hasHighlightedChild ? 'text-yellow-300' : 'text-amber-300'}`}
          >
            <div className="ml-2 pl-2 border-l border-dashed border-gray-500 text-xs space-y-1 pt-2">
              {value.map((item: any, index: number) => {
                const itemPath = `${newPath}/${index}`;
                const isItemHighlighted = isHybridMode && changedPaths.has(itemPath);
                const hasItemHighlightedChild = isHybridMode && Array.from(changedPaths).some(p => p.startsWith(`${itemPath}/`));
                const itemDefaultOpen = !isHybridMode || hasItemHighlightedChild || (isItemHighlighted && (typeof item !== 'object' || item === null));
                const itemHighlightClass = isItemHighlighted ? 'bg-yellow-800/40 border border-yellow-600/60 rounded-md -mx-1 px-1' : '';

                if (typeof item === 'object' && item !== null && !Array.isArray(item)) {
                  let summary;
                  const firstKey = Object.keys(item)[0];
                  if (firstKey) {
                      const firstValue = item[firstKey];
                      if (firstValue !== null && (typeof firstValue === 'string' || typeof firstValue === 'number') && String(firstValue).trim() !== '') {
                          summary = String(firstValue);
                      }
                  }
                  if (!summary) {
                     summary = `项目 ${index + 1}`;
                  }

                  return (
                    <div key={itemPath} className={itemHighlightClass}>
                      <CollapsibleSection
                        title={summary}
                        defaultOpen={itemDefaultOpen}
                        titleClassName={`text-sm font-medium truncate ${isItemHighlighted || hasItemHighlightedChild ? 'text-yellow-300' : 'text-purple-400'}`}
                      >
                         <div className="ml-2 pl-2 border-l border-gray-600">
                           {renderDynamicStateRecursive(item, itemPath, turnIdx, onUpdate, changedPaths, aiCallMode)}
                         </div>
                      </CollapsibleSection>
                    </div>
                  );
                } else {
                  return (
                    <div key={itemPath} className={`flex justify-between items-center py-0.5 ${itemHighlightClass}`}>
                      <span className="text-gray-400 text-xs mr-1">{index}:</span>
                      <EditableStatusValue path={itemPath} value={item} isHighlighted={isItemHighlighted} turnIndex={turnIdx} onUpdate={onUpdate} />
                    </div>
                  );
                }
              })}
            </div>
          </CollapsibleSection>
        </div>
      );
    } else {
      return (
        <div key={newPath} className={`flex justify-between items-start my-1 py-0.5 ${highlightClass}`}>
          <span className="text-gray-300 capitalize text-sm whitespace-nowrap mr-2">{displayKey}:</span>
          <EditableStatusValue path={newPath} value={value} isHighlighted={isHighlighted} turnIndex={turnIdx} onUpdate={onUpdate} />
        </div>
      );
    }
});

export const renderDynamicState = (state: DynamicGameState | undefined, turnIdx: number, onUpdate: (turnIndex: number, path: string, value: any) => void, changedPaths: Set<string>, aiCallMode: AiCallMode) => {
    if (!state || Object.keys(state).length === 0) return <p className="text-gray-500 italic">状态信息为空。</p>;
    return <div className="space-y-1.5">{renderDynamicStateRecursive(state, '', turnIdx, onUpdate, changedPaths, aiCallMode)}</div>;
};
